package com.example.baiduai.tools;

import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author wangyizhu
 * @version "1.8.0_131"
 * @email 2641956765@qq.com
 * @desc: 该类是一个工具类，在当前项目中，该类主要完成从HttpServletRequest中读取文件数据的功能
 * @Time 2022/09/22 9:54
 */


public class FileTools {
    /**
     * 该方法用于通过HttpServletRequest对象中获取文件数据并返回
     *
     * @param req
     */
    public static final int BuFFER_SIZE = 2048;

    public static byte[] getFileDataByRequest(HttpServletRequest req) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream inputStream = null;
        try {
            DiskFileItemFactory disk = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(disk);
            fileUpload.setHeaderEncoding("utf-8");
            //上下文
            ServletRequestContext context = new ServletRequestContext(req);
            List<FileItem> fileItems = fileUpload.parseRequest(context);
            for (int i = 0; i < fileItems.size(); i++) {
                FileItem item = fileItems.get(i);
                //true：正常的表单 false:文件
                if (!item.isFormField()) {
                    //如果fileItem不是正常表单，就按文件读
                    inputStream = item.getInputStream();
                    byte[] buff = new byte[BuFFER_SIZE];
                    int length = 0;
                    while ((length = inputStream.read(buff)) != -1) {
                        outputStream.write(buff, 0, length);
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return outputStream.toByteArray();
    }

    /**
     * byte[] 转字符串
     * @param byteArray
     * @return
     */
    public static String byteArrayToStr(byte[] byteArray) {
        if (byteArray == null) {
            return null;
        }
        String str = new String(byteArray);
        return str;
    }
}
